<script setup lang="ts">
import { ref, reactive, watch, onMounted, onUnmounted, nextTick } from "vue";
import ReTable from "@/components/ReTable/index.vue";
import ReHeaderSearch from "@/components/ReHeaderSearch/index.vue";
import { useSettingStoreHook } from "@/store/modules/settings";
import ReNewDialog from "@/components/ReNewDialog/index.vue";
import ReUpload from "@/components/ReUpload/index.vue";
import ReImageDialog from "@/components/ReImageDialog/index.vue";
import { EditorUpload } from "@/components/ReEditor";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import type { Action } from "element-plus";
defineOptions({
  name: "shopList"
});
interface ValueType {
  val: {
    buttonType: string;
  };
  row: object;
}
interface shopFormType {
  up_menu: string;
  title: string;
  image: string;
  cost_price: string;
  price: string;
  lucky_money: string;
  inventory: string;
  fee_price: string;
  description: string;
  sort: string;
  status: string;
}
const pureSetting = useSettingStoreHook();
const showViewer = ref(false);
const imageUrl = ref("");
const dialogViewVisible = ref(false);
const dialogTitle = ref("");
const ruleFormRef = ref<FormInstance>();
watch(
  () => pureSetting.url,
  (newValue, oldValue) => {
    if (newValue) {
      imageUrl.value = newValue;
      showViewer.value = true;
    }
  },
  {
    immediate: true,
    deep: true
  }
);
// 关闭查看器
const closeViewer = () => {
  showViewer.value = false;
  pureSetting.setUrl("");
};
const deleteModal = () => {
  ElMessageBox.confirm("确定要删除选中的商品吗?", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
    })
    .catch((action: Action) => {
      ElMessage({ type: "info", message: "取消删除" });
    });
};
watch(
  () => pureSetting.buttonInfo,
  (newValue, oldValue) => {
    if (Object.keys(newValue).length !== 0) {
      let value = newValue as ValueType;
      switch (value.val.buttonType) {
        case "delete":
          deleteModal();
          break;
        case "edit":
          console.log("编辑按钮", newValue);
          dialogTitle.value = "修改商品";
          dialogViewVisible.value = true;
          break;
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
);
const shopForm = reactive<shopFormType>({
  up_menu: "",
  title: "",
  image: "",
  cost_price: "",
  price: "",
  lucky_money: "",
  inventory: "",
  fee_price: "",
  description: "",
  sort: "",
  status: "1"
} as shopFormType);
const rules = reactive<FormRules>({
  up_menu: [{ required: true, message: "请选择上级菜单", trigger: "blur" }],
  title: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  image: [{ required: true, message: "请上传商品图片", trigger: "blur" }],
  cost_price: [
    { required: true, message: "请输入成本价", trigger: "blur" },
    { type: "number", message: "请输入数字", trigger: "blur" }
  ],
  price: [
    { required: true, message: "请输入价格", trigger: "blur" },
    { type: "number", message: "请输入数字", trigger: "blur" }
  ],
  lucky_money: [{ type: "number", message: "请输入数字", trigger: "blur" }],
  inventory: [
    { required: true, message: "请输入库存", trigger: "blur" },
    { type: "number", message: "请输入数字", trigger: "blur" }
  ],
  fee_price: [{ type: "number", message: "请输入数字", trigger: "blur" }],
  description: [
    { required: true, message: "请输入商品描述", trigger: "blur" },
    { min: 2, max: 200, message: "长度在 2 到 200 个字符", trigger: "blur" }
  ],
  sort: [
    { required: true, message: "请输入排序", trigger: "blur" },
    { type: "number", message: "请输入数字", trigger: "blur" }
  ],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }]
});
const upMenuOptions = reactive([
  { label: "苹果全家桶", value: "1" },
  { label: "电子竞技", value: "2" },
  { label: "休闲娱乐", value: "3" }
]);
const dialogImageSelectVisible = ref(false);
const imageType = ref("");
const handleGetCreate = () => {
  dialogTitle.value = "添加商品";
  dialogViewVisible.value = true;
};
const handleGetDeleteIds = (deleteIds: string[]) => {
  deleteModal();
};
const handleCloseDialog = () => {
  console.log("关闭弹窗");
  resetForm(ruleFormRef.value);
};
const handleConfirmDialog = () => {
  console.log("确认弹窗");
  submitForm(ruleFormRef.value);
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      resetForm(formEl);
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogViewVisible.value = false;
};
const handleSelctImage = type => {
  imageType.value = type;
  dialogImageSelectVisible.value = true;
};
const handleGetImage = (arr: any) => {
  shopForm[imageType.value] = arr[0].url;
  dialogImageSelectVisible.value = false;
  imageUrl.value = "";
};
const handleCloseImageDialog = () => {
  dialogImageSelectVisible.value = false;
};
const getEditorContent = (value: string) => {
  shopForm.description = value;
};
</script>
<template>
  <div class="shop-list-container">
    <el-image-viewer
      v-if="showViewer"
      :url-list="[imageUrl]"
      @close="closeViewer"
    />
    <el-card shadow="hover" class="mb-2">
      <ReHeaderSearch tableType="shopList" />
    </el-card>
    <ReTable
      class="content-body"
      type="shopList"
      create-btn-text="添加商品"
      delete-btn-text="删除选中商品"
      @delete="handleGetDeleteIds"
      @create="handleGetCreate"
    />
    <ReNewDialog
      :visible="dialogViewVisible"
      :dialogTitle="dialogTitle"
      @close="handleCloseDialog"
      @confirm="handleConfirmDialog"
    >
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="shopForm"
          :rules="rules"
          label-width="140px"
        >
          <el-form-item label="上级菜单" prop="up_menu">
            <el-select v-model="shopForm.up_menu" placeholder="请选择上级菜单">
              <el-option
                v-for="item in upMenuOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="shopForm.title" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品图片" prop="image">
            <div>
              <div class="flex items-center">
                <ReUpload class="mr-3" />
                <el-button @click="handleSelctImage('image')">
                  选择图片
                </el-button>
                <ReImageDialog
                  :visible="dialogImageSelectVisible"
                  @confirm="handleGetImage"
                  @close="handleCloseImageDialog"
                />
              </div>
              <div v-if="shopForm.image != ''" class="mt-3">
                <el-image
                  style="width: 100px; height: 100px; border-radius: 10px"
                  :src="shopForm.image"
                  fit="fill"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="成本价" prop="cost_price">
            <el-input
              v-model="shopForm.cost_price"
              type="number"
              placeholder="请输入成本价"
            />
          </el-form-item>
          <el-form-item label="商品售价" prop="price">
            <el-input
              v-model="shopForm.price"
              type="number"
              placeholder="请输入商品售价"
            />
          </el-form-item>
          <el-form-item label="幸运币售价" prop="lucky_money">
            <el-input
              v-model="shopForm.lucky_money"
              type="number"
              placeholder="请输入幸运币售价"
            />
          </el-form-item>
          <el-form-item label="库存" prop="inventory">
            <el-input
              v-model="shopForm.inventory"
              type="number"
              placeholder="请输入库存"
            />
          </el-form-item>
          <el-form-item label="手续费" prop="fee_price">
            <el-input
              v-model="shopForm.fee_price"
              type="number"
              placeholder="请输入手续费"
            />
          </el-form-item>
          <el-form-item label="商品介绍" prop="description">
            <EditorUpload @onValue="getEditorContent" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="shopForm.sort"
              type="number"
              placeholder="请输入排序"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="shopForm.status">
              <el-radio value="1" size="large">启用</el-radio>
              <el-radio value="0" size="large">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </template>
    </ReNewDialog>
  </div>
</template>
